package com.time.company.components;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.MultiImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.sina.weibo.sdk.utils.Utility;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.app.AppConfig;
import com.time.company.app.WXManager;
import com.time.company.base.BaseActivity;
import com.time.company.base.BasePW;
import com.time.company.components.login.ForgetPsdActivity;
import com.time.company.components.login.LoginActivity;
import com.time.company.components.popup.ExitPW;
import com.time.company.components.popup.SharePW;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.Share;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ShareUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.views.ProgressWebView;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.listener.ResponseCallback;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.LoginParameters;
import com.time.company.webserver.request.requestsParamters.TaskParameters;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.durban.Controller;
import com.yanzhenjie.durban.Durban;
import com.yanzhenjie.nohttp.BasicBinary;
import com.yanzhenjie.nohttp.Binary;
import com.yanzhenjie.nohttp.FileBinary;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadQueue;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhy.base.fileprovider.FileProvider7;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * webView
 * Created by Bing on 2016/8/24.
 * E-mail is tx16bing@163.com
 */
public class WebDetailActivity extends BaseActivity implements
        View.OnClickListener, JsListener, WbShareCallback {

    private static final int HEAD_AVATAR_REQUEST_CODE = 101;
    private static final int CALL_PHONE_REQUEST_CODE = 102;
    private static final int APP_SHARE_REQUEST_CODE = 103;
    private static final int DOWNLOAD_APK_REQUEST_CODE = 104;
    private static final int SHARE_PW_REQUEST_CODE = 105;

    private static final int DURBAN_HEAD_AVATAR_REQUEST_CODE = 200;

    public static final String EXTRA_FLAG = "extra_flag";
    public static final String EXTRA_TITLE = "extra_title";
    public static final String EXTRA_WEB_ADDRESS = "extra_web_address";
    public static final String EXTRA_PIC_ADDRESS = "extra_pic_address";
    private String flag, title, webAddress, picAddress;

    private LinearLayout mParent;
    private RelativeLayout rlNav;
    private ImageView ivBack, ivShare;
    private ProgressWebView mWebView;
    private TextView tvTitle;

    private static final int LOGOUT_WHAT = 0;
    private static final int SHARE_WHAT = 1;

    private WindowManager.LayoutParams attributes;
    private ExitPW exitPW;
    private SharePW sharePW;

    // 联系客服的电话号码
    private String curTelephone, curVersionPath;

    // 分享请求信息
    public WbShareHandler shareHandler;
    private String curChannel, curCommand, curId;
    private boolean isAct;

    public static void start(Activity activity, String flag, String webAddress) {
        Intent intent = new Intent(activity, WebDetailActivity.class);
        intent.putExtra(EXTRA_FLAG, flag);
        intent.putExtra(EXTRA_WEB_ADDRESS, webAddress);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String flag, String webAddress, String title) {
        Intent intent = new Intent(activity, WebDetailActivity.class);
        intent.putExtra(EXTRA_FLAG, flag);
        intent.putExtra(EXTRA_WEB_ADDRESS, webAddress);
        intent.putExtra(EXTRA_TITLE, title);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_detail);
        flag = getIntent().getStringExtra(EXTRA_FLAG);
        if (TextUtils.isEmpty(getIntent().getStringExtra(EXTRA_TITLE))) {
            title = " ";
        } else {
            title = getIntent().getStringExtra(EXTRA_TITLE);
        }
        webAddress = getIntent().getStringExtra(EXTRA_WEB_ADDRESS);
        picAddress = getIntent().getStringExtra(EXTRA_PIC_ADDRESS);
        assignsView();

        // Init sina share
        shareHandler = new WbShareHandler(this);
        shareHandler.registerApp();
    }

    private void assignsView() {
        mParent = findView(R.id.ll_parent);
        rlNav = findView(R.id.rl_web_details_navigation);
        ivBack = findView(R.id.iv_back);
        ivShare = findView(R.id.iv_web_share);
        mWebView = findView(R.id.web_view);
        tvTitle = findView(R.id.tv_title_of_webView);

        rlNav.setVisibility(TextUtils.equals(flag, getString(R.string.task_time_marker)) ? View.VISIBLE : View.GONE);
        tvTitle.setVisibility(TextUtils.equals(flag, getString(R.string.task_time_marker)) ? View.VISIBLE : View.GONE);
        tvTitle.setText(title);
        ivShare.setVisibility(TextUtils.equals(flag, getString(R.string.task_time_marker)) ? View.VISIBLE : View.GONE);

        ivBack.setOnClickListener(this);
        ivShare.setOnClickListener(this);
        mWebView.setJsListener(this);
        mWebView.loadUrl(webAddress);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (mWebView.canBack()){
                    mWebView.toBack();
                }else {
                    finish();
                }
                break;

            case R.id.iv_web_share:
                //微信，朋友圈，微博
                andPermission(SHARE_PW_REQUEST_CODE, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE});
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 404:
                // 用户从设置中回来，无论有没有开启所需要的权限
//                ToastUtils.showShort("从设置中回来");
                break;

            case DURBAN_HEAD_AVATAR_REQUEST_CODE:
                // 裁剪回调
                ArrayList<String> mImageList = Durban.parseResult(data);
                uploadAvatar(getString(R.string.command_uploadHeadImg), mImageList, "headPic");
                break;

            default:
                break;

        }
    }

    @Override
    public void jsGoBack() {
        finish();
    }

    @Override
    public void jsAvatar() {
        // 相册,拍照
        andPermission(HEAD_AVATAR_REQUEST_CODE, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA});
    }

    @Override
    public void jsSuggestion() {
        // Nothing to do
    }

    @Override
    public void jsCommunicate() {
        // Nothing to do
    }

    @Override
    public void jsHiddenBottomTab(String tag, String url) {
        if (TextUtils.equals("false", tag)) {
            // 不隐藏主界面底部导航栏
        }
        if (!TextUtils.isEmpty(url)) {
            String mUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress()).append(url).toString();
            WebDetailActivity.start(this, tag, mUrl);
        }
    }

    @Override
    public void jsShare(String channel, String type, String id) {
        Logger.e("Channel " + channel + " Type " + type + " Id " + id);
        curChannel = channel;
        curId = id;
        if (TextUtils.equals("活动详情", type)) {
            curCommand = getString(R.string.command_shareActivities);
            isAct = true;
        } else if (TextUtils.equals("参加活动成功", type)) {
            curCommand = getString(R.string.command_shareJoinActActivitiesSuccess);
            isAct = true;
        } else if (TextUtils.equals("荣誉", type)) {
            curCommand = getString(R.string.command_shareHonor);
            isAct = false;
        } else {
            return;
        }
        andPermission(APP_SHARE_REQUEST_CODE, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE});
    }

    @Override
    public void jsClearCache() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showShort("清除成功");
            }
        });
    }

    @Override
    public void jsUpdateVersion(String url) {
//        curVersionPath = url;
//        andPermission(DOWNLOAD_APK_REQUEST_CODE, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE});
    }

    @Override
    public void jsTelephone(String number) {
        curTelephone = number;
        andPermission(CALL_PHONE_REQUEST_CODE, new String[]{Manifest.permission.CALL_PHONE});
    }

    @Override
    public void jsReset() {
        // 重置密码
        ForgetPsdActivity.start(this, getString(R.string.psd_reset_flag));
    }

    @Override
    public void jsExit() {
        // 退出登录
        if (exitPW == null || !exitPW.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    launchExit();
                }
            });
        }
    }

    private void andPermission(int requestCode, String[] permissions) {
        AndPermission.with(this)
                .requestCode(requestCode)
                .permission(permissions)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(WebDetailActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == HEAD_AVATAR_REQUEST_CODE) {
                AppConfig.getInstance().initDir();
                // 表示相册的存储的权限申请通过
                Album.image(WebDetailActivity.this) // 选择图片。
                        .multipleChoice()
                        .requestCode(200)
                        .camera(true)
                        .columnCount(3)
                        .selectCount(1)
                        .widget(Widget.newDarkBuilder(WebDetailActivity.this)
                                .title("图片")
                                .statusBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                                .toolBarColor(ContextCompat.getColor(application, R.color.colorPrimary))
                                .navigationBarColor(ContextCompat.getColor(application, android.R.color.black)) // Android5.0+的虚拟导航栏颜色。
                                .mediaItemCheckSelector(Color.WHITE, Color.GREEN) // 图片或者视频选择框的选择器。
                                .bucketItemCheckSelector(
                                        ContextCompat.getColor(application, R.color.colorPrimary),
                                        ContextCompat.getColor(application, R.color.colorPrimary)) // 切换文件夹时文件夹选择框的选择器。
                                .build())
                        .onResult(new Action<ArrayList<AlbumFile>>() {
                            @Override
                            public void onAction(int requestCode, @NonNull ArrayList<AlbumFile> result) {
                                if (null != result && !result.isEmpty()) {
                                    String path = result.get(0).getPath();
                                    durban(path);
                                }
                            }
                        })
                        .onCancel(new Action<String>() {
                            @Override
                            public void onAction(int requestCode, @NonNull String result) {
                            }
                        })
                        .start();
            } else if (requestCode == CALL_PHONE_REQUEST_CODE) {
                // 表示打电话的权限申请通过
                //联系我们
                Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + curTelephone));
                callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (ActivityCompat.checkSelfPermission(WebDetailActivity.this,
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                startActivity(callIntent);
            } else if (requestCode == APP_SHARE_REQUEST_CODE) {
                AppConfig.getInstance().initDir();
                shareRequest();
            } else if (requestCode == DOWNLOAD_APK_REQUEST_CODE) {
                AppConfig.getInstance().initDir();
                downLoadFile(curVersionPath);
            } else if (requestCode == SHARE_PW_REQUEST_CODE){
                AppConfig.getInstance().initDir();
                if (sharePW == null || !sharePW.isShowing()) {
                    launchShare();
                } else {
                    return;
                }
            }
        }



        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            AppConfig.getInstance().initDir();
            // 即使是用户选择了不在询问还是会toast该提示语
            if (requestCode == HEAD_AVATAR_REQUEST_CODE) {
                ToastUtils.showShort(getString(R.string.permission_camera_gallery));
            } else if (requestCode == CALL_PHONE_REQUEST_CODE) {
                ToastUtils.showShort(getString(R.string.permission_call_telephone));
            } else if (requestCode == APP_SHARE_REQUEST_CODE || requestCode == DOWNLOAD_APK_REQUEST_CODE) {
                ToastUtils.showShort(getString(R.string.permission_external_storage));
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(WebDetailActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(WebDetailActivity.this, 404).show();
            }
        }
    };

    // 图片裁剪
    private void durban(String paths) {
        String outPath = AppConfig.getInstance().APP_PATH_ROOT;
        Durban.with(this)
                // 裁剪界面的标题。
                .title("图片裁剪")
                .statusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                .toolBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                .navigationBarColor(ContextCompat.getColor(this, android.R.color.black))
                // 图片路径list或者数组。
                .inputImagePaths(paths)
                // 图片输出文件夹路径。
                .outputDirectory(outPath)
                // 裁剪图片输出的最大宽高。
                .maxWidthHeight(300, 300)
                // 裁剪时的宽高比。
                .aspectRatio(1, 1)
                // 图片压缩格式：JPEG、PNG。
                .compressFormat(Durban.COMPRESS_JPEG)
                // 图片压缩质量，请参考：Bitmap#compress(Bitmap.CompressFormat, int, OutputStream)
                .compressQuality(90)
                // 裁剪时的手势支持：ROTATE, SCALE, ALL, NONE.
                .gesture(Durban.GESTURE_ALL)
                .controller(Controller.newBuilder()
                        .enable(false)
                        .rotation(true)
                        .rotationTitle(true)
                        .scale(true)
                        .scaleTitle(true)
                        .build())
                .requestCode(DURBAN_HEAD_AVATAR_REQUEST_CODE)
                .start();
    }

    public void shareRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            Request request = new BasicRequest(AddressManager.getInstance().getAddress());
            TaskParameters parameters = new TaskParameters();
            parameters.setCommand(curCommand);
            parameters.setUserId(application.getAccount());
            if (isAct) {
                parameters.setActivitiesId(curId);
            } else {
                parameters.setHonorUserId(curId);
            }
            parameters.setThirdParty(curChannel);
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this,
                    SHARE_WHAT, false, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    private void launchShare() {
        final Window window = getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        sharePW = new SharePW(this, mParent);
        sharePW.setOnItemClickListener(new BasePW.OnItemClickListener<Object>() {
            @Override
            public void onItemClick(final int type, Object result) {

                if (type == resources.getInteger(R.integer.share_type_wx)) {
                    curChannel = application.getString(R.string.share_channel_friend);
                } else if (type == resources.getInteger(R.integer.share_type_wx_publish)) {
                    curChannel = application.getString(R.string.share_channel_moment);
                } else if (type == resources.getInteger(R.integer.share_type_qq)) {
                    curChannel = application.getString(R.string.share_channel_qq);
                } else if (type == resources.getInteger(R.integer.share_type_qq)) {
                    curChannel = application.getString(R.string.share_channel_qq_zone);
                } else if (type == resources.getInteger(R.integer.share_type_wb)) {
                    curChannel = application.getString(R.string.share_channel_wei_bo);
                } else {
                    return;
                }
                ToastUtils.showShort("Channel " + curChannel);

            }
        });
        sharePW.showAtLocation(mParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        sharePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    /**
     * 下载apk
     *
     * @param apkPath
     * @return
     */
    private void downLoadFile(final String apkPath) {

        String fileName = "time_company.apk";
        final File file = new File(AppConfig.getInstance().APP_PATH_ROOT, fileName);
        DownloadQueue queue = NoHttp.newDownloadQueue();
        DownloadRequest downloadRequest = NoHttp.createDownloadRequest(apkPath, file.toString(), true);
        downloadRequest.setRetryCount(5);
        downloadRequest.setCancelSign(toString());
        queue.add(2, downloadRequest, new DownloadListener() {
            // 下载出现异常
            @Override
            public void onDownloadError(int what, Exception exception) {
                ToastUtils.showShort(getString(R.string.download_error));
            }

            // 开始下载
            @Override
            public void onStart(int what, boolean isResume, long rangeSize,
                                Headers responseHeaders, long allCount) {
                ToastUtils.showShort(getString(R.string.download_ing));
            }

            // 下载进度变化
            @Override
            public void onProgress(int what, int progress, long fileCount, long speed) {
                if (what == 2) {
                    //显示下载进度条
                }
            }

            // 下载完成
            @Override
            public void onFinish(int what, String filePath) {
                if (what == 2) {
                    File file = new File(filePath);
                    openFile(file);
                }
            }

            // 下载取消或者终止
            @Override
            public void onCancel(int what) {
                if (what == 2) {
                    ToastUtils.showShort(getString(R.string.download_cancel));
                }
            }
        });
    }

    /**
     * 打开APK程序代码
     *
     * @param file
     */
    private void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        FileProvider7.setIntentDataAndType(
                this, intent,
                "application/vnd.android.package-archive",
                file, true);
        startActivity(intent);
        finish();
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()) {
            if (what == LOGOUT_WHAT) {
                application.destroyData();
                Intent intent = new Intent(this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            } else if (what == SHARE_WHAT) {
                final Share share = basicBean.parseData(Share.class);
                if (share == null) return;

                ShareUtils.getInstance().getSharePicPath(share.getPicUrl(), "share.jpg", new ShareUtils.ShareCallback() {
                    @Override
                    public void onSucceed(String path) {
                        String localPicUrl = path;
                        if (TextUtils.isEmpty(localPicUrl)) {
                            localPicUrl = ShareUtils.getInstance().getSharePicPath("share.jpg");
                        }
                        if (TextUtils.equals(curChannel, getString(R.string.share_channel_friend))) {
                            //　分享给微信朋友
                            shareMoment(share, false, localPicUrl);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_moment))) {
                            //　分享给微信朋友圈
                            shareMoment(share, true, localPicUrl);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_wei_bo))) {
                            // 分享给微博
                            shareWeibo(share, localPicUrl);
                        } else {
                            return;
                        }
                    }
                });
            }
        } else {
//            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    private void shareMoment(Share share, boolean isTimelineCb, String localPicUrl) {
        WXManager.instance().sendWebPageToWX(
                isTimelineCb,
                share.getAddress(),
                TextUtils.isEmpty(share.getTitle()) ? " " : share.getTitle(),
                share.getDescribe(),
                localPicUrl);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    private void shareWeibo(Share share, String localPicUrl) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.textObject = getTextObj(share);
        weiboMessage.imageObject = getImageObj();
        weiboMessage.mediaObject = getWebpageObj(share);
        weiboMessage.multiImageObject = getMultiImageObject(share, localPicUrl);
        shareHandler.shareMessage(weiboMessage, false);

    }

    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj(Share share) {
        TextObject textObject = new TextObject();
        textObject.text = share.getTitle();
        return textObject;
    }

    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_share_wb);
        imageObject.setImageObject(bitmap);
        return imageObject;
    }

    private BaseMediaObject getWebpageObj(Share share) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = share.getTitle();
        mediaObject.description = getString(R.string.app_name);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_logo);
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = share.getAddress();
        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }

    private MultiImageObject getMultiImageObject(Share share, String localPicUrl) {
        MultiImageObject multiImageObject = new MultiImageObject();
        //pathList设置的是本地本件的路径,并且是当前应用可以访问的路径，现在不支持网络路径（多图分享依靠微博最新版本的支持，所以当分享到低版本的微博应用时，多图分享失效
        // 可以通过WbSdk.hasSupportMultiImage 方法判断是否支持多图分享,h5分享微博暂时不支持多图）多图分享接入程序必须有文件读写权限，否则会造成分享失败
        ArrayList<Uri> pathList = new ArrayList<>();
        pathList.add(FileProvider7.getUriForFile(this, new File(localPicUrl)));
        multiImageObject.setImageList(pathList);
        return multiImageObject;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null != shareHandler) {
            shareHandler.doResultIntent(intent, this);
        }
    }

    @Override
    public void onWbShareSuccess() {
        ToastUtils.showLong("分享成功");
    }

    @Override
    public void onWbShareCancel() {
        ToastUtils.showLong("分享取消");
    }

    @Override
    public void onWbShareFail() {
        ToastUtils.showLong("分享失败");
    }


    /**
     * 上传图片
     */
    private void uploadAvatar(String command, List<String> paths, String key) {
        if (!NetWorkUtils.isNetAvailable(application)) {
            ToastUtils.showShort(application.getString(R.string.network_error));
            return;
        }
        if (paths == null) {
            ToastUtils.showShort("请上传有效的图片路径");
            return;
        }

        if (paths.isEmpty()) {
            ToastUtils.showShort("上传图片不能为空");
            return;
        }

        LoginParameters parameters = new LoginParameters();
        parameters.setCommand(command);
        parameters.setUserId(application.getAccount());

        String url = null;
        try {
            url = new StringBuilder().append(AddressManager.getInstance().getAddress())
                    .append("?").append(getString(R.string.command))
                    .append("=").append(command)
                    .append("&").append(getString(R.string.data))
                    .append("=").append(URLEncoder.encode(new Gson().toJson(parameters), "UTF-8"))
                    .toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Request request = NoHttp.createStringRequest(url, RequestMethod.POST);
        request.add(application.getString(R.string.command), parameters.getCommand());
        request.add(application.getString(R.string.platform), parameters.getPlatform());
        request.add("userId", application.getAccount());
        List<Binary> binaries = new ArrayList<>();
        for (String path : paths) {
            File file = new File(path);
            BasicBinary fileBinary = new FileBinary(file);
            binaries.add(fileBinary);
        }
        request.add(key, binaries);
        request.setCancelSign(toString());
        WebServerManager.getInstance().add(this, request, new ResponseCallback<String>() {
                    @Override
                    public void onSucceed(int what, Response<String> response) {
                        String bean = response.get();
                        BasicBean basicBean = new Gson().fromJson(bean, BasicBean.class);

                        if (basicBean == null) {
                            return;
                        }

                        if (basicBean.isSuccess()) {
                            ToastUtils.showShort("上传成功");
                            startActivity(new Intent(WebDetailActivity.this, MainActivity.class)
                                    .putExtra(getString(R.string.tab_title),
                                            getString(R.string.tab_profile_title)));
                        } else {
                            ToastUtils.showShort(basicBean.getMsg());
                        }

                    }

                    @Override
                    public void onFailed(int what, Object tag, Exception exception, long networkMillis) {
                        ToastUtils.showShort("发送失败");
                    }
                },
                409, false, true, true);
    }

    private void launchExit() {
        final Window window = this.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        exitPW = new ExitPW(this, mParent);
        exitPW.setOnItemClickListener(new BasePW.OnItemClickListener() {
            @Override
            public void onItemClick(final int type, Object result) {
                if (type == resources.getInteger(R.integer.pw_exit_confirm)) {
                    logout();
                }
            }
        });
        exitPW.showAtLocation(mParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        exitPW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    /**
     * 退出登录
     */
    private void logout() {
        if (NetWorkUtils.isNetAvailable(this)) {
            Request request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_logoutForCompany));
            parameters.setUserId(application.getAccount());
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, LOGOUT_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canBack()) {
            mWebView.toBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mWebView != null) {
            mParent.removeView(mWebView);
            mWebView.removeAllViews();
        }

        if (null != exitPW) {
            exitPW.dismiss();
            exitPW = null;
        }

    }

}
